package com.woniu.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.commons.exception.YogaException;
import com.woniu.commons.model.Result;
import com.woniu.commons.util.JwtUtil;
import com.woniu.commons.util.RedisUtil;
import com.woniu.model.dto.CoachDto;
import com.woniu.model.dto.CoachPageDto;
import com.woniu.model.entity.YCoach;
import com.woniu.model.form.*;
import com.woniu.model.param.*;
import com.woniu.service.YCoachService;
import com.woniu.util.FileUtil;
import com.woniu.util.OSSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 胡歌
 * @since 2024年05月22日
 */
@RestController
@RequestMapping("/yCoach")
@Api(tags = "教练操作信息的一些接口")
public class YCoachController {
    @Resource
    private YCoachService coachService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private OSSUtil ossUtil;
    /**
     * 发送注册验证码
     * @param
     * @return
     */
    @GetMapping("/sendCoachRegisterCode")
    @ApiOperation(value = "发送注册验证码给教练")
    public Result sendCoachRegisterCode(@RequestParam("mobile") String mobile){
        coachService.sendRegisterCode(mobile);
        return Result.newInstance(null).setMsg("发送注册验证码成功").setCode(200);
    }
    /**
     * 教练注册的接口
     * @param
     * @return
     */
    @ApiOperation(value = "教练注册的接口")
    @PostMapping("/checkCode")
    public Result checkCode(@RequestBody CodeCoachRegisterForm form)throws Exception{
        coachService.CodeCoachRegister(BeanUtil.toBean(form, CodeCoachRegisterParam.class));
        return Result.newInstance(null).setCode(200).setMsg("注册成功");
    }

    /**
     * 完善教练端的其他信息
     * @param form
     * @return
     * @throws YogaException
     */
    @PostMapping("/updateCoachBase")
    @ApiOperation(value = "完善教练端的详细信息")
    public Result updateCoachBase(@RequestBody UpdateCoachBaseForm form, @RequestHeader String token)throws YogaException{
        String refreshToken = redisUtil.get(token);
        Integer coachId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("id").toString());
        UpdateCoachBaseParam param = BeanUtil.toBean(form, UpdateCoachBaseParam.class);
        param.setCoachId(coachId);
        coachService.updateCoachBase(param);
        return Result.newInstance(null).setMsg("完善成功").setData(200);
    }
    /**
     *教练发送登录短信
     * @param
     * @return
     */
    @ApiOperation(value = "教练发送登录短信")
    @GetMapping("/LoginCodePhone")//发送登录短信
    public Result LoginCodePhone(@RequestParam("mobile") String mobile)throws Exception{
        coachService.LoginCodePhone(mobile);
        return Result.getResult().setMsg("发送登录短信成功").setCode(200);
    }
    /**
     *教练手机号登录
     * @param
     * @return
     */
    @ApiOperation(value = "教练手机号登录")
    @PostMapping("/phoneLogin")
    public Result phoneLogin(@RequestBody CoachCodeLoginForm form, HttpServletResponse response)throws Exception{
        CoachDto coachDto = coachService.codeLogin(BeanUtil.toBean(form, CoachCodeLoginParam.class));
        Map<String, Object> map = BeanUtil.beanToMap(coachDto);
        //生成短的token
        HashMap<String, Object> accessBody = new HashMap<>();
        //使用雪花算法生成随机的不同的短token，确保不重复
        String random = new Snowflake(1, 1).nextIdStr();
        accessBody.put("random",random);
        //生成短token
        String accessToken = JwtUtil.createToken(accessBody, 15);
        //生成长token
        String refreshToken = JwtUtil.createToken(map, 3*24*60);
        //将长的token保存到redis中
        redisUtil.set(accessToken,refreshToken,3*24*60*60);//3天有效时间
        //相应token前端
        response.setHeader("token",accessToken);
        response.setHeader("Access-Control-Expose-Headers","token");
        return Result.newInstance(CoachDto.class).setData(coachDto).setMsg("登录成功");
    }


    /**
     *教练账号密码登录
     * @param
     * @return
     */
    @ApiOperation(value = "教练账号密码登录")
    @PostMapping("/coachLogin")
    public Result coachLogin(@RequestBody coachLoginForm form, HttpServletResponse resp)throws Exception{
        CoachDto coachDto = coachService.coachLogin(BeanUtil.toBean(form, coachLoginParam.class));
        Map<String, Object> map = BeanUtil.beanToMap(coachDto);
        HashMap<String, Object> accessBody=new HashMap<String, Object>();
        String random=new Snowflake(1,1).nextIdStr();
        accessBody.put("random",random);
        String accessToken= JwtUtil.createToken(accessBody,15);
        String refreshToken=JwtUtil.createToken(map,3*24*60);
        redisUtil.set(accessToken,refreshToken,3*24*60*60);//3天有效时间
        resp.setHeader("token",accessToken);
        resp.setHeader("Access-Control-Expose-Headers","token");
        return Result.newInstance(CoachDto.class).setData(coachDto).setMsg("登录成功");
    }


    /**
     *教练修改个人头像
     * @param
     * @return
     */
    @PostMapping("/updateImage")
    @ApiOperation("教练修改个人头像")
    public Result updateImage(UpdateCoachImageForm form, @RequestHeader String token)throws Exception{
        String refreshToken = redisUtil.get(token);
        Integer coachId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("id").toString());
        if (!FileUtil.isImageFile(form.getImage().getInputStream())){
            throw  new YogaException(9999,"文件类型错误");
        }
        String oldName = form.getImage().getOriginalFilename();
        String suffix = oldName.substring(oldName.lastIndexOf("."));
        String name = UUID.randomUUID().toString();
        String filePath = ossUtil.uploadFile(form.getImage().getInputStream(), name + suffix, "woniupengyuyan");
        UpdateCoachImageParam param = BeanUtil.toBean(form, UpdateCoachImageParam.class);
        param.setCoachId(coachId);
        param.setImage(filePath);
        coachService.updateImage(param);
        return Result.getResult().setMsg("修改个人头像成功");
    }

    /**
     *教练修改个人昵称
     * @param
     * @return
     */
    @Transactional
    @PostMapping("/updateMessage")
    @ApiOperation("教练修改个人昵称")
    public  Result updateMessage(@RequestBody UpdateMessageForm form, @RequestHeader String token)throws Exception{
        String refreshToken = redisUtil.get(token);
        Integer userId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("id").toString());
        UpdateMessageParam param = BeanUtil.toBean(form, UpdateMessageParam.class);
        param.setCoachId(userId);
        YCoach coach = coachService.updateMessage(param);
        return Result.newInstance(YCoach.class).setData(coach).setMsg("修改成功");
    }


    /**
     * 根据id查找教练信息
     * @param id
     * @return
     */
    @GetMapping("/byId/{id}")
    @ApiOperation("根据id查找教练信息")
    public Result<CoachDto> byId(@PathVariable("id") Integer id){
        YCoach coach = coachService.getById(id);
        return Result.newInstance(CoachDto.class).setData(BeanUtil.toBean(coach,CoachDto.class));
    }
    /**
     * 分页查询教练
     *
     * @param form pageNum; pageSize;
     * @return
     * @throws YogaException
     */
    @GetMapping("/loadPageCoach")
    @ApiOperation(value = "教练分页查询接口")
    public Result loadPageCoach( LoadPageCoachForm form) throws YogaException {
        Page<CoachPageDto> page = coachService.loadPageCoach(BeanUtil.toBean(form, LoadPageCoachParam.class));
        return Result.newInstance(null).setMsg("查询成功").setCode(200).setData(page);
    }


    /**
     * 展示所有教练
     * @return
     */

    @GetMapping("/seatInfoList")
    @ApiOperation("展示所有教练")
    public Result<List<CoachDto>> seatInfoList(){
        List<YCoach> infoList = coachService.list();
        List<CoachDto> list=new ArrayList<>();
        for (YCoach info : infoList) {
            list.add(BeanUtil.toBean(info,CoachDto.class));
        }
        return Result.newListInstance(CoachDto.class).setData(list);
    }
    /**
     *
     * @param coachPass 修改密码 需要填写旧密码 然后在填写新密码  新旧密码不能相同
     * @param token
     * @return
     * @throws Exception
     */
    @Transactional
    @GetMapping("/UpdateCoachPassword")
    @ApiOperation("修改密码")
    public  Result UpdateCoachPassword(String coachPass,@RequestHeader String token)throws Exception{
        String refreshToken = redisUtil.get(token);
        Integer coachId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("id").toString());
        UpdateCoachPasswordParam param = new UpdateCoachPasswordParam();
        param.setCoachId(coachId);
        param.setNewPassword(coachPass);
        coachService.UpdateCoachPassword(param);
        return Result.getResult().setMsg("修改密码成功");
    }
    /**
     *form 教练自己修改状态
     * @param
     * @return
     */
    @GetMapping("/CoachUpdateState")
    @Transactional
    @ApiOperation("教练自己修改状态")
    public Result updateCoach(Integer coachState,@RequestHeader String token){
        String refreshToken = redisUtil.get(token);
        Integer coachId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("id").toString());
        AdminUpdateCoachStateParam param = new AdminUpdateCoachStateParam();
        param.setCoachId(coachId);
        param.setCoachState(coachState);
        coachService.updateCoach(param);
        return Result.getResult().setMsg("修改状态成功");
    }


    /**
     *form 修改教练状态 参数教练ID 以及要修改的状态值
     * @param
     * @return
     */
    @GetMapping("/updateCoachState")
    @Transactional
    @ApiOperation("修改教练状态")
    public Result updateCoachState(YCoach coach){
        UpdateCoachStateParam param = new UpdateCoachStateParam();
        param.setCoachId(coach.getCoachId());
        param.setCoachState(coach.getCoachState());
        coachService.updateCoachState(param);
        return Result.getResult().setMsg("修改状态成功");
    }


    /**
     *form 修改教练种类
     * @param
     * @return
     */
    @GetMapping("/updateCoachTypeId")
    @Transactional
    @ApiOperation("修改教练类型")
    public Result updateCoachTypeId(Integer coachTypeId,@RequestHeader String token){
        String refreshToken = redisUtil.get(token);
        Integer coachId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("id").toString());
        updateCoachTypeIdParam param = new updateCoachTypeIdParam();
        param.setCoachId(coachId);
        param.setCoachTypeId(coachTypeId);
        coachService.updateCoachTypeId(param);
        return Result.getResult().setMsg("修改教练种类成功");
    }



    /**
     *教练的手机号修改 需要给之前的电话号码发短信
     *
     * @param
     * @return
     */
    @GetMapping("/UpdateCoachPhone")
    @ApiOperation(value = "发送修改手机号验证码的接口")
    public Result UpdateCoachPhone(@RequestParam("mobile") String mobile) throws Exception {
        coachService.UpdateCoachPhone(mobile);
        return Result.newInstance(null).setMsg("发送修改手机号验证码成功").setCode(200);
    }
    /**
     *教练的手机号修改
     * 需要传的值  老的手机号 发送的验证码code  在传入新的手机号
     * @param
     * @return
     */
    @PostMapping("/codeCoachUpdate")
    @ApiOperation(value = "教练修改手机号的接口")
    public Result codeUpdate(@RequestBody CodeCoachUpdateForm form) throws  Exception{
        coachService.codeUpdate(BeanUtil.toBean(form, CodeCoachUpdateParam.class));
        return Result.newInstance(null).setCode(200).setMsg("修改手机号成功");
    }

    /**
     * 查询教练个人信息
     * @param token
     * @return
     */

    /**
     * 通过token载入教练账号信息
     * @param token
     * @return
     */
    @GetMapping("/loadCoachByToken")
    @Transactional
    @ApiOperation("通过token载入教练账号信息")
    public Result<YCoach> loadCoachByToken(@RequestHeader String token){
        String refreshToken = redisUtil.get(token);
        Integer coachId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("id").toString());
        YCoach coach = coachService.loadCoachByToken(coachId);
        return Result.newInstance(YCoach.class).setMsg("通过token载入教练账号信息成功").setData(coach);
    }

    @GetMapping("/findCoachInfo")
    @ApiOperation("查询教练个人信息")
    public Result findCoachInfo(@RequestHeader String token){
        String refreshToken = redisUtil.get(token);
        //获取token
        Integer  coachId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("id").toString());
        YCoach coachInfo = coachService.findCoachInfo(coachId);
        return  Result.newInstance(YCoach.class).setData(coachInfo).setMsg("查询教练个人信息成功");
    }

    /**
     * 根据id查找教练信息
     * @param coachId
     * @return
     */
    @GetMapping("/loadCoachById")
    @Transactional
    @ApiOperation("根据id查找教练信息")
    public Result<YCoach> loadCoachById(Integer coachId){
        YCoach coach = coachService.loadCoachByToken(coachId);
        return Result.newInstance(YCoach.class).setMsg("根据id查找教练信息信息成功").setData(coach);
    }
}

